#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "thread.hpp"

using std::cout;
using std::endl;

uint16_t client_port = 0;
std::string client_ip = "";
static void useage(const char *str)
{
    cout << "Useage:\n\t" << str << " ipaddr port\n"
         << endl;
}

// 单进程版收发会阻塞 不能同时进行
// 使用多线程解决，一个线程收，一个线程发
void *send(void *args)
{
    ThreadData *td = (ThreadData *)args;
    int sock = *(int*)(td->_args);
    std::string name = td->_name;

    std::string send_message;
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(client_port);
    server.sin_addr.s_addr = inet_addr(client_ip.c_str());

    while (1)
    {
        
        std::cout << "send message:#";
        std::getline(std::cin, send_message);
        if (send_message == "quit")
            break;
        sendto(sock, send_message.c_str(), sizeof(send_message), 0, (struct sockaddr *)&server, sizeof server);
    }

    return nullptr;
}
void *recv(void *args)
{
    ThreadData *td = (ThreadData *)args;
    int sock = *(int*)(td->_args);
    std::string name = td->_name;

    char read_buffer[1024];
    while (1)
    {
        memset(read_buffer, 0, sizeof(read_buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t read_size = recvfrom(sock, read_buffer, sizeof read_buffer, 0, (struct sockaddr *)&temp, &len);
        if (read_size > 0)
        {
            read_buffer[read_size] = 0;
            //std::cout <<"server recv#:"<< read_buffer << std::endl;
            LogMessage(NORMAL,"secver recv#: %s",read_buffer);
        }
    }
    return nullptr;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        useage(argv[0]);
        exit(-1);
    }
    // 创建套接字
    int client_socket = socket(AF_INET, SOCK_DGRAM, 0);
    if (client_socket < 0)
    {
        LogMessage(FATAL, "%d,%s", errno, strerror(errno));
        exit(-1);
    }
    // 获取ip和port
    client_port = atoi(argv[2]); // 转整形
    client_ip = argv[1];

    Thread *sender = new Thread(1, send, (void *)&client_socket);
    Thread *recver = new Thread(2, recv, (void *)&client_socket);
    sender->start();
    recver->start();

    sender->join();
    recver->join();

    delete sender;
    delete recver;
    close(client_socket);
    return 0;
}